package cn.acac.yygh.user.controller.user;

import cn.acac.yygh.enums.AuthStatusEnum;
import cn.acac.yygh.model.user.UserInfo;
import cn.acac.yygh.result.R;
import cn.acac.yygh.user.service.UserInfoService;
import cn.acac.yygh.utils.JwtHelper;
import cn.acac.yygh.vo.user.LoginVo;
import cn.acac.yygh.vo.user.UserAuthVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user/userInfo")
@Api("/用户操作")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户登录接口
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo){
        Map<String,Object> userMap = userInfoService.login(loginVo);
        return R.ok().setData(userMap);
    }

    /**
     * 获取请求头中的token信息
     * @param request
     * @return
     */
    @GetMapping("/user")
    public R getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        // 使用JWT工具解析token信息
        Long userId = JwtHelper.getUserId(token);
        // 调用业务层处理请求
        UserInfo userInfo = userInfoService.getUserInfo(userId);
        return R.ok().setData("userInfo",userInfo);
    }

    /**
     * 将用户认证的信息传递过来进行保存
     * @param request
     * @param userAuthVo
     * @return
     */
    @PutMapping("/updateUserInfo")
    public R updateUserInfo(HttpServletRequest request, UserAuthVo userAuthVo){
        String token = request.getHeader("token");
        // 根据token获取用户id
        Long userId = JwtHelper.getUserId(token);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        // 调用业务层更新数据
        userInfoService.updateById(userInfo);
        return R.ok();
    }
}
